Skip to content

fix usage-limit cooldown persistence - #354

Closed
ndycode wants to merge 1 commit into
mainfrom
git-split/20260405-pr350-cooldown
Closed

fix usage-limit cooldown persistence#354
ndycode wants to merge 1 commit into
mainfrom
git-split/20260405-pr350-cooldown

Conversation

@ndycode

@ndycode ndycode commented Apr 4, 2026

Copy link
Copy Markdown
Owner

Summary

What Changed

  • Tightened usage-limit handling across request/error classification and quota scheduling so cooldown state persists and propagates correctly instead of bouncing accounts back into ready selection too early.
  • Added focused regression coverage across account state, fetch helpers, scheduler behavior, and the plugin entrypoint.

Validation

  • npm run lint
  • npm run typecheck
  • npm test
  • npm test -- test/documentation.test.ts
  • npm run build
  • npm test -- test/accounts.test.ts test/fetch-helpers.test.ts test/index.test.ts test/preemptive-quota-scheduler.test.ts

Docs and Governance Checklist

  • No docs updates were needed; this is cooldown/state handling only.

Risk and Rollback

  • Risk level: medium
  • Rollback plan: revert 00bbcba

Additional Notes

note: greptile review for oc-chatgpt-multi-auth. cite files like lib/foo.ts:123. confirm regression tests + windows concurrency/token redaction coverage.

Greptile Summary

this pr tightens usage-limit cooldown propagation across three layers: accounts.ts and preemptive-quota-scheduler.ts now use Math.max to preserve the longest reset time instead of blindly overwriting it, and the index.ts fallback 429 path is fully wired into the same backoff/scheduler pipeline as the primary path. the retry-after cap is raised from 5 minutes to 7 days, and natural-language usage-limit messages are parsed for both clock-time ("try again at 6:26 AM") and duration ("try again in 2 hours") hints.

Confidence Score: 5/5

safe to merge — all findings are P2 style/cleanup concerns with no correctness impact

the core Math.max fix in accounts.ts and preemptive-quota-scheduler.ts is correct and well-tested; the fallback 429 path is now consistent with the primary path; no P0/P1 issues found

lib/preemptive-quota-scheduler.ts (secondary slot data loss is benign but worth tracking); test/fetch-helpers.test.ts (indentation inconsistency on one migrated test)

Important Files Changed

Filename Overview
lib/accounts.ts markRateLimitedWithReason now uses Math.max to preserve the longest reset time — correct and minimal fix
lib/preemptive-quota-scheduler.ts markRateLimited preserves max reset across overlapping calls; secondary.usedPercent is silently cleared on each invocation
lib/request/fetch-helpers.ts retry-after cap raised from 5 min to 7 days; clock-time and duration natural-language parsing added with correct 12-hour AM/PM handling
index.ts fallback 429 path gains full scheduler/backoff propagation; explicit body stream cancel removed from fallback cleanup
test/accounts.test.ts regression coverage for Math.max cooldown preservation added; clean vitest structure
test/fetch-helpers.test.ts good coverage for natural-language parsing and cap increase; one migrated test has inconsistent indentation
test/index.test.ts getCurrentWorkspace mock removed cleanly; fallback 429 coverage updated
test/preemptive-quota-scheduler.test.ts markRateLimited persistence across overlapping updates well-covered with deterministic fake-timer assertions

Sequence Diagram

sequenceDiagram
    participant C as Client
    participant P as Plugin fetch handler
    participant B as getRateLimitBackoff
    participant S as PreemptiveQuotaScheduler
    participant A as AccountManager

    C->>P: request
    P->>P: primary account fetch → 429
    P->>B: getRateLimitBackoff(index, quotaKey, retryAfterMs)
    B-->>P: { delayMs }
    P->>P: cooldownMs = max(delayMs, retryAfterMs)
    P->>S: markRateLimited(quotaScheduleKey, cooldownMs)
    Note over S: nextReset = max(existingReset, now+cooldownMs)
    P->>A: markRateLimitedWithReason(account, cooldownMs, ...)
    Note over A: resetAt = max(currentResetAt, now+cooldownMs)

    alt cooldownMs ≤ short retry threshold
        P->>P: sleep(addJitter(cooldownMs)) then retry
    else
        P-->>C: propagate 429 with cooldownMs wait
    end

    Note over P: fallback account path (new)
    P->>P: fallback fetch → 429
    P->>P: handleErrorResponse(fallbackResponse)
    P->>B: getRateLimitBackoff(fallbackIndex, fallbackQuotaKey, retryAfterMs)
    B-->>P: { delayMs }
    P->>P: cooldownMs = max(delayMs, retryAfterMs)
    P->>S: markRateLimited(fallbackScheduleKey, cooldownMs)
    P->>A: markRateLimitedWithReason(fallbackAccount, cooldownMs, 'quota', ...)
    P->>P: continue to next fallback
Loading

Fix All in Codex

Prompt To Fix All With AI
This is a comment left during a code review.
Path: test/fetch-helpers.test.ts
Line: 1181-1188

Comment:
**test indented at wrong describe scope**

this test was migrated from the old top-level `it('caps retryAfterMs at 5 minutes'` but its indentation (1 tab) was not updated to match the surrounding nested group (3 tabs, lines 1147–1179 and 1190+). it still runs and passes, but it is not inside the same `describe` block as the other cap tests, so grouping and scoping are inconsistent.

```suggestion
			it('caps retryAfterMs at 7 days', async () => {
				const body = { error: { message: 'rate limited', retry_after_ms: 10 * 24 * 60 * 60 * 1000 } };
				const response = new Response(JSON.stringify(body), { status: 429 });
				
				const { rateLimit } = await handleErrorResponse(response);
				
				expect(rateLimit?.retryAfterMs).toBe(7 * 24 * 60 * 60 * 1000);
			});
```

How can I resolve this? If you propose a fix, please make it concise.

---

This is a comment left during a code review.
Path: lib/preemptive-quota-scheduler.ts
Line: 221-228

Comment:
**secondary slot usedPercent silently dropped on markRateLimited**

`secondary: {}` wipes any existing `secondary.usedPercent` from a prior `update()` call. the secondary reset timestamp is correctly folded into `nextResetAtMs` on the primary slot, so deferral is preserved during the active 429 window. however, once the cooldown expires and the snapshot is pruned, the near-exhaustion signal on the secondary quota is gone until the next successful response restores it via `update()`. this is benign in the common path but worth noting for observability: a request that lands between cooldown expiry and the next successful header could skip the `quota-near-exhaustion` deferral branch.

How can I resolve this? If you propose a fix, please make it concise.

---

This is a comment left during a code review.
Path: index.ts
Line: 2148-2150

Comment:
**original fallback response body stream not cancelled**

the old code explicitly called `fallbackResponse.body?.cancel()` (best-effort cleanup) before moving to the next account. the replacement `handleErrorResponse(fallbackResponse)` calls `safeReadBody` via `response.clone().text()`, which consumes the *clone's* body but leaves the original undici stream open. on long-lived http/2 connections this can delay socket reuse until gc. adding an explicit cancel after the read would restore the original safety net:

```typescript
const { response: handledFallbackResponse, rateLimit: fallbackRateLimit } =
    await handleErrorResponse(fallbackResponse);
try { await fallbackResponse.body?.cancel(); } catch { /* best effort */ }
```

How can I resolve this? If you propose a fix, please make it concise.

Reviews (1): Last reviewed commit: "fix usage-limit cooldown persistence" | Re-trigger Greptile

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Credits must be used to enable repository wide code reviews.

@coderabbitai

coderabbitai Bot commented Apr 4, 2026

Copy link
Copy Markdown
Contributor

Warning

Rate limit exceeded

@ndycode has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 29 minutes and 56 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 29 minutes and 56 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 9c77970e-a7fc-4962-b898-49c1fbe8ffe4

📥 Commits

Reviewing files that changed from the base of the PR and between cbce5f5 and 00bbcba.

📒 Files selected for processing (8)
  • index.ts
  • lib/accounts.ts
  • lib/preemptive-quota-scheduler.ts
  • lib/request/fetch-helpers.ts
  • test/accounts.test.ts
  • test/fetch-helpers.test.ts
  • test/index.test.ts
  • test/preemptive-quota-scheduler.test.ts
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch git-split/20260405-pr350-cooldown
✨ Simplify code
  • Create PR with simplified code
  • Commit simplified code in branch git-split/20260405-pr350-cooldown

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@ndycode

ndycode commented Apr 5, 2026

Copy link
Copy Markdown
Owner Author

Superseded by merged rebuild #355 and the follow-up release work now on main.

@ndycode ndycode closed this Apr 5, 2026
@ndycode
ndycode deleted the git-split/20260405-pr350-cooldown branch April 12, 2026 06:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant